package cn.itcast.usermanage.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.itcast.usermanage.pojo.DataResult;
import cn.itcast.usermanage.pojo.PageResult;
import cn.itcast.usermanage.pojo.User;
import cn.itcast.usermanage.service.AutoUserService;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private AutoUserService userService;

	/**
	 * 页面跳转,进入用户列表页面
	 *//*
	@RequestMapping("/users")
	public String toUserList() {

		return "users";
	}
*/
	/**
	 * 分页查询方法
	 * 
	 * @param page
	 * @param rows
	 * @return
	 */
	@RequestMapping("/list")
	@ResponseBody
	public DataResult<User> queryUserListByPage(
			@RequestParam(value = "page", defaultValue = "1") Integer page,
			@RequestParam(value = "rows", defaultValue = "10") Integer rows) {

		return userService.queryUserListByPage(page, rows);
	}
	@RequestMapping("/save")
	@ResponseBody
	public PageResult saveUser(User user){
		try {
			userService.saveUser(user);
			return PageResult.ok();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return PageResult.error();
		}
	}
	@RequestMapping("/update")
	@ResponseBody
	public PageResult updateUser(User user){
		try {
			userService.updateUser(user);
			return PageResult.ok();
			
		} catch (Exception e) {
			e.printStackTrace();
			return PageResult.error();
		}
	}
	@PostMapping("/export/excel")
	public ModelAndView exportExcel(@RequestParam(value = "page", defaultValue = "1") Integer page,
			@RequestParam(value = "rows", defaultValue = "10") Integer rows){
		//创建模型和视图对象并指定视图名称
		System.out.println(page+"ssss"+rows);
		ModelAndView mv = new ModelAndView("excelView");
		//查询分页数据
		DataResult<User> result = userService.queryUserListByPage(page, rows);
		//添加数据到模型
		mv.addObject("users", result.getRows());
		return mv;
	}
}
